import {
  getSignList,
  getTaskCate,
  getTaskList,
  getShopList,
  getSignPush,
  addSign,
  getNotice,
} from "@/static/js/pointsMall.js";
import {
  getUserInfo
} from "@/static/js/my.js";
import {
  completeTask
} from "@/static/js/points.js";
export default {
  data() {
    return {
      switchValue: false,
      topTips: ['活动中心正式上线了，快来参与活动啊', '积分可兑换限时商品，请前往商城兑换好礼', '商城商品不定时补货，请持续关注'],
      tabIndex: 1,
      tabList: [], //任务分类
      taskList: [], //任务列表

      userInfo: {}, //用户信息

      shopList: [], //商品列表
      pageShow: false,
      showSign: false, //签到提醒弹窗
      signContent: "关闭提醒后，可能会错过签到，是否确定关闭？",

      signObj: {},
      signList: [], //签到列表

      btnClick: false,

      signPic: "https://xzcs-public-files.oss-cn-beijing.aliyuncs.com/static/activityCenter/gold-icon.png",
      signedPic: "https://xzcs-public-files.oss-cn-beijing.aliyuncs.com/static/activityCenter/sign-sure.png",
      judgeNotifyFlag: false, //判断是否点击去设置
      showPointsTips: false, //任务完成提示
      pointsObj: {}, //任务完成对象
    };
  },
  onLoad() {
    this.getTaskCate();
    this.getShopList();
  },
  onShow() {
    this.getTaskList();
    this.getSignList();
    this.getUserInfo();
    // this.getTopTips();
    if (this.judgeNotifyFlag) {
      this.judgeNotify();
    }
  },
  methods: {
    //获取用户信息
    getUserInfo() {
      getUserInfo().then((res) => {
        this.userInfo = res.data;
        this.pageShow = true;
        this.switchValue = res.data.sign_remind == 1 ? true : false;
        uni.setStorageSync("userInfo", res.data);
      });
    },

    //获取签到列表
    async getSignList() {
      let res = await getSignList();
      if (res.code === 1) {
        if (res.data.is_sign == 0) {
          this.btnClick = false;
        } else {
          this.btnClick = true;
        }
        this.signObj = res.data;
        this.signList = res.data.signlist.list;
      } else {
        this.$tools.msg(res.msg);
      }
    },

    //获取任务分类
    async getTaskCate() {
      let res = await getTaskCate();
      if (res.code === 1) {
        this.tabList = res.data;
      } else {
        this.$tools.msg(res.msg);
      }
    },

    //跳转积分明细
    bambooView() {
      uni.navigateTo({
        url: "/pointsMall/pointsDetail/index",
      });
    },

    // applet_type  1：非小程序 2：问题库 3：法规库 4：模板专区  5：问答
    //cate_id 1.每日任务，2.新手任务，3.限时任务
    //获取任务列表
    async getTaskList() {
      let obj = {
        applet_type: 1,
        cate_id: this.tabIndex,
      };
      let res = await getTaskList(obj);
      if (res.code === 1) {
        this.taskList = res.data;
      } else {
        this.$tools.msg(res.msg);
      }
    },

    //获取商品列表
    async getShopList() {
      let res = await getShopList();
      if (res.code === 1) {
        this.shopList = res.data.slice(0, 4);
      } else {
        this.$tools.msg(res.msg);
      }
    },

    //签到回调事件
    switchChange(e) {
      if (!e) {
        this.showSign = true;
      } else {
        this.changeSignStatus(1);
      }
    },

    // 签到更改后台状态
    async changeSignStatus(status) {
      let res = await getSignPush({
        status
      });
      if (res.code == 1) {
        if (status == 0) {
          this.switchValue = false;
          this.$tools.msg("订阅签到提醒关闭");
        } else {
          this.switchValue = true;
          this.$tools.msg("订阅签到提醒成功");
        }
        setTimeout(() => {
          this.getUserInfo();
        }, 800);
      } else {
        this.$tools.msg(res.msg);
      }
    },

    //任务选项点击事件
    tabClick(val) {
      this.tabIndex = val.id;
      this.getTaskList();
    },

    //签到点击事件
    async signClick() {
      const innerAudioContext = uni.createInnerAudioContext();
      innerAudioContext.autoplay = true;
      innerAudioContext.src =
        "https://xzcs-public-files.oss-cn-beijing.aliyuncs.com/static/activityCenter/money_video.MP3";
      innerAudioContext.onPlay(() => {
        console.log("签到成功");
      });
      let obj = {
        list_id: this.signList[this.signObj.continue_day].id,
      };
      let res = await addSign(obj);
      if (res.code === 1) {
        this.getSignList();
        this.getUserInfo();
      } else {
        this.$tools.msg(res.msg);
      }
    },

    //商品列表
    goShopList() {
      uni.navigateTo({
        url: "/pointsMall/shopList/index",
      });
    },

    //商品详情
    goShopDetail(val) {
      uni.navigateTo({
        url: "/pointsMall/shopDetail/index?id=" + val.id,
      });
    },

    goRules() {
      uni.navigateTo({
        url: "/pointsMall/pointsRules/index",
      });
    },

    // 请求顶部滚动消息
    async getTopTips() {
      let res = await getNotice();
      if (res.code == 1) {
        let list = res.data;
        let arr = [];
        list.forEach((item) => {
          arr.push(item.title);
        });
        this.topTips = arr;
        console.log(this.topTips);
      } else {
        this.$tools.msg(res.msg);
      }
    },

    //任务点击事件
    taskClick(e) {
      if (e.user_count == e.count) return;

      // 非tabBar栏页面
      const navigateToUrlMap = {
        A1: "/library/problem/index/index",
        A2: "",
        A3: "/pages/model/graduate/index",
        A4: "/quiz/ask/index",
        B1: "/pages/my/homePage/edit",
        B2: "/pages/my/homePage/edit",
        B3: "/pages/my/homePage/edit",
        B6: "/pages/pcDsc/index",
        C1: "/pages/my/settings/index",
        C2: "/pages/my/invite/myInvite",
        C3: "/enterpriseServer/publishDemand/index",
      };

      // tabBar栏页面
      const switchTabUrlMap = {
        A5: "/quiz/index/index",
        B7: "/pages/my/index/index",
      };

      if (e.code in navigateToUrlMap) {
        let url = navigateToUrlMap[e.code];
        if (url == "") {
          this.$tools.msg("敬请期待");
          return;
        }
        uni.navigateTo({
          url: url,
        });
      } else if (e.code in switchTabUrlMap) {
        uni.switchTab({
          url: switchTabUrlMap[e.code],
        });
      }
      if (e.code == "B4") {
        this.openSystem();
        this.judgeNotifyFlag = true;
      }
    },

    // 打开到设置页面看有没有打开通知设置
    openSystem() {
      uni.setStorageSync("goSystemSettings", true);
      let osName = plus.os.name.toLowerCase();
      if (osName == "android") {
        console.log("osName:" + osName);
        let main = plus.android.runtimeMainActivity();
        let pkName = main.getPackageName();
        let uid = main.getApplicationInfo().plusGetAttribute("uid");
        let Intent = plus.android.importClass("android.content.Intent");
        let Build = plus.android.importClass("android.os.Build");
        let intent = "";
        console.log("Androd SDK_INT:" + Build.VERSION.SDK_INT);

        if (Build.VERSION.SDK_INT >= 26) {
          // android 8.0引导
          intent = new Intent("android.settings.APP_NOTIFICATION_SETTINGS");
          intent.putExtra("android.provider.extra.APP_PACKAGE", pkName);
        } else if (Build.VERSION.SDK_INT >= 21) {
          //android 5.0-7.0
          intent = new Intent("android.settings.APP_NOTIFICATION_SETTINGS");
          intent.putExtra("app_package", pkName);
          intent.putExtra("app_uid", uid);
        } else {
          //(<21)其他--跳转到该应用管理的详情页
          let Settings = plus.android.importClass("android.provider.Settings");
          let Uri = plus.android.importClass("android.net.Uri");
          intent = new Intent();
          intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
          let uri = Uri.fromParts("package", main.getPackageName(), null);
          intent.setData(uri);
        }
        // 跳转
        main.startActivity(intent);
      } else if (osName == "ios") {
        let UIApplication = plus.ios.import("UIApplication");
        let app = UIApplication.sharedApplication();
        let enabledTypes = 0;
        if (app.currentUserNotificationSettings) {
          let settings = app.currentUserNotificationSettings();
          enabledTypes = settings.plusGetAttribute("types");
        } else {
          //针对低版本ios系统
          enabledTypes = app.enabledRemoteNotificationTypes();
        }
        plus.ios.deleteObject(app);
        if (0 == enabledTypes) {
          // 未开启通知
          uni.showModal({
            title: "提示",
            content: "开启通知权限后才能收到提示消息哦。",
            delCancel: false,
            confirmVal: "去开启",
            cancelVal: "取消",
          })
            .then((res) => {
              let UIApplication = plus.ios.import("UIApplication");
              let NSURL = plus.ios.import("NSURL");
              let setting = NSURL.URLWithString("app-settings:");
              let application = UIApplication.sharedApplication();
              application.openURL(setting);
              plus.ios.deleteObject(setting);
              plus.ios.deleteObject(application);
            });
        }
      }
    },

    //判断是否打开通知设置
    judgeNotify() {
      let osName = plus.os.name.toLowerCase();
      if (osName == "android") {
        let main = plus.android.runtimeMainActivity();
        let NotificationManagerCompat = plus.android.importClass(
          "androidx.core.app.NotificationManagerCompat"
        );
        let packageNames = NotificationManagerCompat.from(main);
        let notificationEnabled = packageNames.areNotificationsEnabled();
        if (!notificationEnabled) {
          console.log("未开启通知");
        } else {
          console.log("已开启通知");
          this.completeQuest("B4");
        }
      } else if (osName == 'ios') {
        let UIApplication = plus.ios.import("UIApplication");
        let app = UIApplication.sharedApplication();
        let enabledTypes = 0;
        if (app.currentUserNotificationSettings) {
          let settings = app.currentUserNotificationSettings();
          enabledTypes = settings.plusGetAttribute("types");
        } else {
          //针对低版本ios系统
          enabledTypes = app.enabledRemoteNotificationTypes();
        }
        if (enabledTypes == 0) {
          console.log("未开启通知");
        } else {
          this.completeQuest("B4");
        }
      }
    },

    //完成任务
    completeQuest(code) {
      completeTask({
        code
      }).then((res) => {
        if (res.code == 1) {
          this.showPointsTips = true;
          this.pointsObj = res.data;
        }
      });
      setTimeout(() => {
        this.showPointsTips = false;
        this.getTaskList();
      }, 3000);
    },

    onConfirm() {
      this.changeSignStatus(0);
      this.showSign = false;
    },

    onCancel() {
      this.showSign = false;
    },
  },
};